import React, { PureComponent, Fragment } from 'react';
import { Table, Alert } from 'antd';
import styles from './index.less';

function initTotalList(columns) {
  const totalList = [];
  columns.forEach(column => {
    if (column.needTotal) {
      totalList.push({ ...column, total: 0 });
    }
  });
  return totalList;
}

class StandardTable extends PureComponent {
  constructor(props) {
    super(props);
    const { columns } = props;
    const needTotalList = initTotalList(columns);

    this.state = {
      selectedRowKeys: [],
      needTotalList,
    };
  }

  componentWillReceiveProps(nextProps) {
    // clean state
    if (nextProps.selectedRows.length === 0) {
      const needTotalList = initTotalList(nextProps.columns);
      this.setState({
        selectedRowKeys: [],
        needTotalList,
      });
    }
  }

  handleRowSelectChange = (selectedRowKeys, selectedRows) => {
    let needTotalList = [...this.state.needTotalList];
    needTotalList = needTotalList.map(item => {
      return {
        ...item,
        total: selectedRows.reduce((sum, val) => {
          return sum + parseFloat(val[item.dataIndex], 10);
        }, 0),
      };
    });

    if (this.props.onSelectRow) {
      this.props.onSelectRow(selectedRows);
    }

    this.setState({ selectedRowKeys, needTotalList });
  };

  handleTableChange = (pagination, filters, sorter) => {
    this.props.onChange(pagination, filters, sorter);
  };

  cleanSelectedKeys = () => {
    this.handleRowSelectChange([], []);
  };

  render() {
    const { selectedRowKeys, needTotalList } = this.state;
    const { data: { list, page,count },pagination, loading, columns, expandedRowRender, expandRowByClick,onRow } = this.props;
    
    console.log('page:',page,'count:',count)
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      defaultCurrent: page,
      total : count,
    };

    const rowSelection = {
      selectedRowKeys,
      onChange: this.handleRowSelectChange,
      getCheckboxProps: record => ({
        disabled: record.disabled,
      }),
    };
    if(!pagination){
      return (
        <div className={styles.standardTable}>
          <Table
            loading={loading}
            rowKey={(r,i)=>(i)}
            dataSource={list}
            columns={columns}
            pagination={false}
          />
        </div>
      );
    }else{
      return (
        <div className={styles.standardTable}>
          <Table
            loading={loading}
            rowKey={(r,i)=>(i)}
            dataSource={list}
            columns={columns}
            expandRowByClick={expandRowByClick}
            expandedRowRender={expandedRowRender}
            pagination={paginationProps}
            onChange={this.handleTableChange}
          />
        </div>
      );
    }
  }
}

export default StandardTable;
